package com.itheima.service.impl;

import com.itheima.mapper.PeopleMapper;
import com.itheima.pojo.People;
import com.itheima.pojo.Result;
import com.itheima.service.LoginService;
import com.itheima.utils.CodeUtils;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class LoginServiceImpl implements LoginService {
    @Autowired
    private PeopleMapper peopleMapper;
    @Override
    public People login(People people) {
        List<People> allPeople = peopleMapper.searchPeople(new People());
        for (int i = 0; i <allPeople.size(); i++) {
            if (people.getAccount().equals(allPeople.get(i).getAccount())&& people.getPassword().equals(allPeople.get(i).getPassword())) {
                return allPeople.get(i);
            }
        }
        return null;
    }

    @Override
    public void register(People people) {
        peopleMapper.insert(people);
    }

    @Override
    public String getCode(String phone) {

        return CodeUtils.generateCode(phone);
    }

    @Override
    public Result loginByPhone(String phone, String code) {
        Claims claims = CodeUtils.parseCode(code, phone);
        if (claims == null){
            return Result.error("验证码错误");
        }
        People people = new People();
        people.setPhone(claims.get("phone").toString());
        List<People> peopleList = peopleMapper.searchPeople(people);
        if (peopleList.isEmpty()){
            return Result.error("找不到该手机号");
        }
        People p= peopleList.get(0);
        String jwt=JwtUtils.generateJwt(p.getId(),p.getName(),p.getRole(),p.getField());
        return Result.success(jwt);
    }
}
